<?php

namespace app\common\model;

use think\Db;
use think\Exception;

class ResumeActivate extends BaseModel
{
    public static $able_add_activate_time = 3; // 单位为月
    public static $able_activate_time = 15 * 86400;
    /**
     * 添加到记录
     * @param $params
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function add($params){
        $company_id = $params['company_id'];
        $mobiles = $params['mobiles'];

        $obj_uids = Member::where('company_id',$company_id)->whereIn('mobile',$mobiles)->column('uid,reg_time','mobile');
        $obj_resume_ids = Resume::whereIn('uid',array_column($obj_uids,'uid'))->column('id','uid');
        // 查询需要激活的企业用户
        //  企业数据
        $companys = Company::where('id','<>',$company_id)->column('id');

        $members = Member::alias('m')->whereIn('company_id',$companys)
            ->whereIn('mobile',$mobiles)
            ->join('resume r','r.uid=m.uid','right')
            ->where('r.download_time','<=',strtotime('-'.self::$able_add_activate_time.' months'))
            ->field('m.uid,mobile,company_id')->select();
        if(count($members) <= 0){
            return false;
        }
        $resume_ids = Resume::whereIn('uid',array_column($members,'uid'))->column('id','uid');
        $time = time();
        // 已存在的数据
        $exists = self::where('obj_company_id',$company_id)
            ->whereIn('obj_uid',array_column($obj_uids,'uid'))
            ->where('add_at','>=',time() - self::$able_activate_time)
            ->column('uid');
        foreach ($members as $member){
            if(!$obj_data = $obj_uids[$member['mobile']]??[]){
                continue;
            }
            if(in_array($member['uid'],$exists)){
                continue;
            }
            $data = [
                'uid' => $member['uid'],
                'company_id' => $member['company_id'],
                'resume_id' => $resume_ids[$member['uid']]??0,
                'obj_uid' => $obj_data['uid'],
                'obj_company_id' => $company_id,
                'add_at' => $time
            ];
            $data['obj_resume_id'] = $obj_resume_ids[$data['obj_uid']];
            $insert_data[] = $data;
        }
//        dolog(__METHOD__,$insert_data??[]);
        !empty($insert_data) && (new self())->allowField(true)->saveAll($insert_data);
        return true;
    }

    /**
     * 获取待激活数量
     * @param $company_id
     * @return int|string
     * @throws \think\Exception
     */
    public static function getNum($company_id){
        return self::where('company_id',$company_id)->where('add_at','>=',time() - self::$able_activate_time)->count();
    }

    public static function handle($company_id){
//        return return_data(200,'正则开发中，敬请期待！');
        $res = self::where('company_id',$company_id)->where('add_at','>=',time() - self::$able_activate_time)->select();
        if(count($res)<=0){
            return return_data(500,'暂无可激活数据');
        }

        // 获取目标数据信息
        $obj_data = self::getObjInfo($res);
//        dd($obj_data);
        // 查询当前企业的员工信息
        $data = self::getCurrentInfo($res);
//        dd($data);

        // 处理更新数据
        $update_resume = $update_candidate = $insert_certificate = $update_contact = $insert_education = [];
        $insert_intention = $insert_language = $insert_work = $update_job_apply = [];
        $insert_candidate = [];
        $delete_certificate = $delete_education = $delete_intention = $delete_language = $delete_work = [];
        foreach ($obj_data as $key => $value){
            if(!$current_data = $data[$key]??[]){
                continue;
            }
            $_insert = [
                'rid' => $current_data['resume_id'],
                'uid' => $current_data['member']['uid']
            ];
            // 简历
            unset($value['resume']['id']);
            $update_resume[] = array_merge($value['resume'],['id'=>$current_data['resume_id'],'uid'=>$current_data['member']['uid']]);
            // 是否进入候选人才
            if( time() - $value['resume']['download_time'] < 3600 * 24 * 7){
                if($current_data['candidate']){
                    $update_candidate[] = array_merge($value['candidate'],['resume_id'=>$current_data['resume_id']]);
                    $update_candidate[] = [
                        'company_id' => $company_id,
                        'resume_id' => $current_data['resume_id'],
                        'status' => 0
                    ];
                }else{
                    $insert_candidate[] = [
                        'company_id' => $company_id,
                        'resume_id' => $current_data['resume_id'],
                        'status' => 0
                    ];
                }
            }
            // 证书
            if($current_data['certificate']){
                foreach ($value['certificate'] as $v){
                    unset($v['id']);
                    $insert_certificate[] = array_merge($v,$_insert);
                }
                $delete_certificate[] = $_insert['rid'];
            }
            // 联系方式
            if($current_data['contact']){
                unset($value['contact']['id']);
                $update_contact[] = array_merge($value['contact'],$_insert);
            }
            // 教育
            if($current_data['education']){
                foreach ($value['education'] as $v){
                    unset($v['id']);
                    $insert_education[] = array_merge($v,$_insert);
                }
                $delete_education[] = $_insert['rid'];
            }
            // 工作意图
            if($current_data['intention']){
                foreach ($value['intention'] as $v){
                    unset($v['id']);
                    $insert_intention[] = array_merge($v,$_insert);
                }
                $delete_intention[] = $_insert['rid'];
            }
            // 语言
            if($current_data['language']){
                foreach ($value['language'] as $v){
                    unset($v['id']);
                    $insert_language[] = array_merge($v,$_insert);
                }
                $delete_language[] = $_insert['rid'];
            }
            // 工作经历
            if($current_data['work']){
                foreach ($value['work'] as $v){
                    unset($v['id']);
                    $insert_work[] = array_merge($v,$_insert);
                }
                $delete_work[] = $_insert['rid'];
            }
            // 投递简历
            if($current_data['job_apply']){
                unset($value['job_apply']['id']);
                $update_job_apply[] = array_merge($value['job_apply'],['resume_id'=>$current_data['resume_id'],'personal_uid'=>$current_data['member']['uid']]);
            }

        }
        $data = [
            [
                'model' =>Resume::class,
                'update_key' => 'id',
                'update' => $update_resume,
                'insert' => [],
                'delete' => [],
            ],
            [
                'model' =>ResumeCandidate::class,
                'update_key' => 'resume_id',
                'update' => $update_candidate,
                'insert' => $insert_candidate,
                'delete' => [],
            ],
            [
                'model' =>ResumeContact::class,
                'update_key' => 'rid',
                'update' => $update_contact,
                'insert' => [],
                'delete' => [],
            ],
            [
                'model' =>ResumeCertificate::class,
                'update_key' => 'rid',
                'update' => [],
                'insert' => $insert_certificate,
                'delete' => $delete_certificate,
            ],
            [
                'model' =>ResumeEducation::class,
                'update_key' => 'rid',
                'update' => [],
                'insert' => $insert_education,
                'delete' => $delete_education,
            ],
            [
                'model' =>ResumeIntention::class,
                'update_key' => 'rid',
                'update' => [],
                'insert' => $insert_intention,
                'delete' => $delete_intention,
            ],
            [
                'model' =>ResumeLanguage::class,
                'update_key' => 'rid',
                'update' => [],
                'insert' => $insert_language,
                'delete' => $delete_language,
            ],
            [
                'model' =>ResumeWork::class,
                'update_key' => 'rid',
                'update' => [],
                'insert' => $insert_work,
                'delete' => $delete_work,
            ],
            [
                'model' =>JobApply::class,
                'update_key' => 'resume_id',
                'update' => $update_job_apply,
                'insert' => [],
                'delete' => [],
            ]
        ];

        $result = self::batchHandleData($data);
        if(!$result){
            return return_data(500,'操作失败');
        }
        // 删除更新的数据
        if(self::where('company_id',$company_id)->whereIn('uid',array_column($res,'uid'))->count()){
            self::where('company_id',$company_id)->whereIn('uid',array_column($res,'uid'))->delete();
        }
        return return_data(200,'操作完成');

    }

    /**
     * 批量处理数据的新增，删除，更新
     * @param $data
     * @return bool
     */
    private static function batchHandleData($data){
        try{
            Db::startTrans();
            foreach ($data as $value){
                $value['update'] && model($value['model'])->updateBatch($value['update'],$value['update_key']);
                if($value['delete']){
                    $model = model($value['model'])->whereIn('rid',$value['delete']);
                    $model->count() && model($value['model'])->whereIn('rid',$value['delete'])->delete();
                }
                $value['insert'] && model($value['model'])->insertAll($value['insert']);
            }
            Db::commit();
            return true;
        }catch (Exception $e){
            Db::rollback();
            dolog('batchHandleDataError',[$e->getMessage(),$e->getLine(),$e->getFile(),$e->getTraceAsString()]);

            return false;
        }

    }

    /**
     * 获取目标信息
     * @param $res
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private static function getObjInfo($res){
        // 获取目标数据
        $obj_uids = array_column($res,'obj_uid');
        $obj_resume_ids = array_column($res,'obj_resume_id');
        //  获取会员数据
        $member = Member::whereIn('uid',$obj_uids)->select();
        //  获取简历库数据
        $resume = Resume::whereIn('id',$obj_resume_ids)->column('*','uid');
        //  获取证书数据
        $certificate = ResumeCertificate::whereIn('rid',$obj_resume_ids)->field('id',true)->select();
        $certificate = model(self::class)->groupBy($certificate,'rid');

        //  获取联系信息数据
        $contact = ResumeContact::whereIn('rid',$obj_resume_ids)->column('*','rid');
        //  获取教育数据
        $education = ResumeEducation::whereIn('rid',$obj_resume_ids)->select();
        $education = model(self::class)->groupBy($education,'rid');
        //  获取工作意图数据
        $intention = ResumeIntention::whereIn('rid',$obj_resume_ids)->select();
        $intention = model(self::class)->groupBy($intention,'rid');
        //  获取语言等级数据
        $language = ResumeLanguage::whereIn('rid',$obj_resume_ids)->select();
        $language = model(self::class)->groupBy($language,'rid');
        //  获取工作经历数据
        $work = ResumeWork::whereIn('rid',$obj_resume_ids)->select();
        $work = model(self::class)->groupBy($work,'rid');
        //  获取投递简历数据
        $job_apply = JobApply::whereIn('resume_id',$obj_resume_ids)->column('*','resume_id');

        $obj_data = [];
        foreach ($member as $value){
            if(!$_resume = $resume[$value['uid']]??[]){
                continue;
            }
            $resume_id = $_resume['id'];
            $obj_data[$value['mobile']]['member'] = $value->toArray();
            $obj_data[$value['mobile']]['resume'] = $_resume;
            $obj_data[$value['mobile']]['certificate'] = $certificate[$resume_id]??[];
            $obj_data[$value['mobile']]['contact'] = $contact[$resume_id]??[];
            $obj_data[$value['mobile']]['education'] = $education[$resume_id]??[];
            $obj_data[$value['mobile']]['intention'] = $intention[$resume_id]??[];
            $obj_data[$value['mobile']]['language'] = $language[$resume_id]??[];
            $obj_data[$value['mobile']]['work'] = $work[$resume_id]??[];
            $obj_data[$value['mobile']]['job_apply'] = $job_apply[$resume_id]??[];
        }
        return $obj_data;
    }

    /**
     *  获取当前企业的信息
     * @param $res
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private static function getCurrentInfo($res){
        // 获取目标数据
        $uids = array_column($res,'uid');
        $resume_ids = array_column($res,'resume_id');
        //  获取会员数据
        $member = Member::whereIn('uid',$uids)->field('uid,mobile')->select();
        //  获取简历库数据
        $resume = Resume::whereIn('id',$resume_ids)->column('id','uid');
        //  获取候选人才信息
        $candidate = ResumeCandidate::whereIn('resume_id',$resume_ids)->group('resume_id')->column('count(*)','resume_id');
        //  获取证书数据
        $certificate = ResumeCertificate::whereIn('rid',$resume_ids)->group('rid')->column('count(*)','rid');
        //  获取联系信息数据
        $contact = ResumeContact::whereIn('rid',$resume_ids)->group('rid')->column('count(*)','rid');
        //  获取教育数据
        $education = ResumeEducation::whereIn('rid',$resume_ids)->group('rid')->column('count(*)','rid');
        //  获取工作意图数据
        $intention = ResumeIntention::whereIn('rid',$resume_ids)->group('rid')->column('count(*)','rid');
        //  获取语言等级数据
        $language = ResumeLanguage::whereIn('rid',$resume_ids)->group('rid')->column('count(*)','rid');
        //  获取工作经历数据
        $work = ResumeWork::whereIn('rid',$resume_ids)->group('rid')->column('count(*)','rid');
        //  获取投递简历数据
        $job_apply = JobApply::whereIn('resume_id',$resume_ids)->group('resume_id')->column('count(*)','resume_id');

        $data = [];
        foreach ($member as $value){
            if(!$resume_id = $resume[$value['uid']]??0){
                continue;
            }
            $data[$value['mobile']]['member'] = $value->toArray();
            $data[$value['mobile']]['resume_id'] = $resume_id;
            $data[$value['mobile']]['candidate'] = $candidate;
            $data[$value['mobile']]['certificate'] = $certificate[$resume_id]??0;
            $data[$value['mobile']]['contact'] = $contact[$resume_id]??0;
            $data[$value['mobile']]['education'] = $education[$resume_id]??0;
            $data[$value['mobile']]['intention'] = $intention[$resume_id]??0;
            $data[$value['mobile']]['language'] = $language[$resume_id]??0;
            $data[$value['mobile']]['work'] = $work[$resume_id]??0;
            $data[$value['mobile']]['job_apply'] = $job_apply[$resume_id]??0;
        }
        return $data;
    }
}
